<script lang="ts" setup>
import { getLyricAPI, getSongUrlAPI, getSongDetailAPI } from '@/services/song'
import { usePlayStore } from '@/stores/modules/play'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import { inject } from 'vue'
import MyHeader from '@/components/header/myHeader.vue'

// 接收页面参数
const query = defineProps<{
  id: number
}>()
const id = query.id
// 歌曲详情
const songDetail = ref<any>()
// 歌词
const lyric = ref<any>()
// 歌词列表
const lyricList = ref<any>([])
// 歌曲url信息
const songUrlInfo = ref<any>()
// 歌曲url
const songUrl = ref<any>()
//音乐播放时间
const currentTime = ref<number>(0)
//歌词滚动位置
const lyricIndex = ref<number>(0)

const playStore = usePlayStore()

// 获取歌曲详情
function getSongDetailData() {
  getSongDetailAPI(id).then((res) => {
    songDetail.value = res
  })
}

// 获取歌曲url
function getSongUrlData() {
  getSongUrlAPI(id).then((res) => {
    songUrlInfo.value = res
    songUrl.value = res.data[0].url
    playSong()
  })
}
// 获取歌词
function getLyricData() {
  getLyricAPI(id).then((res) => {
    lyric.value = res
    // // 歌词格式化
    let re = /\[([^\]]+)\]([^[]+)/g
    res.lrc.lyric.replace(re, ($0: any, $1: any, $2: any) => {
      lyricList.value.push({ time: timeStringToSeconds($1), text: $2 })
    })
    console.log(lyricList.value)
  })
}

// 时间格式转换
function timeStringToSeconds(timeString: string) {
  var arr = timeString.split(':')
  return (parseFloat(arr[0]) * 60 + parseFloat(arr[1])).toFixed(2)
}

//获取全局内部音频实例
const innerAudioContext: any = inject('audioContext')

// 播放音乐
function playSong() {
  console.log(innerAudioContext.paused)

  // 如果有音乐正在播放，则先停止当前音乐
  if (playStore.isPlaying) {
    stopSong()
    currentTime.value = 0
  }
  if (!songUrl.value) {
    uni.showToast({
      title: '音乐地址获取失败',
      icon: 'none',
    })
  }
  // 设置音乐url
  innerAudioContext.src = songUrl.value
  innerAudioContext.startTime = currentTime.value
  console.log(currentTime.value)
  innerAudioContext.play()
}

// 暂停音乐
function stopSong() {
  currentTime.value = innerAudioContext.currentTime
  innerAudioContext.stop()
}

// 监听音乐暂停
innerAudioContext.onStop(() => {
  playStore.isPlaying = false // 更新状态为未播放
  console.log('暂停播放')
  console.log('结束：' + currentTime.value)
})
// 监听音乐播放
innerAudioContext.onPlay(() => {
  playStore.isPlaying = true // 更新状态为播放
  console.log('开始播放')
  console.log('开始：' + currentTime.value)
  rollLyricList()
})

// 歌词滚动定时器
var timer: any
// 歌词滚动
function rollLyricList() {
  clearInterval(timer)
  timer = setInterval(() => {
    //当前播放器时间
    let time = innerAudioContext.currentTime
    //循环歌词数组
    for (var i = 0; i < lyricList.value.length; i++) {
      if (lyricList.value[i].time < time && lyricList.value[i + 1].time > time) {
        lyricIndex.value = i
      }
    }
  }, 50)
}

onLoad(() => {
  getSongDetailData()
  getSongUrlData()
  getLyricData()
})
</script>

<template>
  <MyHeader :title="songDetail?.songs[0].name" />
  <image
    class="needle"
    :class="{ 'needle-play': playStore.isPlaying }"
    src="../../static/images/needle.png"
    mode="scaleToFill"
  />
  <view class="record">
    <image
      class="cover"
      :src="songDetail?.songs[0].al.picUrl"
      :style="`animation-play-state:${playStore.isPlaying ? 'running' : 'paused'}`"
    />
    <view class="btn">
      <view v-if="!playStore.isPlaying" @click="playSong" class="iconfont icon-bofang"></view>
      <view v-else @click="stopSong" class="iconfont icon-zanting"></view>
    </view>
  </view>
  <scroll-view class="lyric-wrap">
    <view class="lyric" :style="{ transform: 'translateY(' + -(lyricIndex - 1) * 82 + 'rpx)' }">
      <view
        class="lyric-item"
        v-for="(item, i) in lyricList"
        :class="{ 'lyric-item-active': lyricIndex === i }"
        :key="item.text"
        >{{ item.text }}</view
      >
    </view>
  </scroll-view>
</template>

<style>
page {
  background: linear-gradient(rgb(55, 99, 123), rgb(16, 28, 35));
  color: #fff;
  width: 100%;
  height: 100%;
}
</style>

<style lang="scss" scoped>
.needle {
  position: relative;
  width: 200rpx;
  height: 180px;
  margin-left: 41%;
  z-index: 999;
  transition: all 0.5s;
  transform-origin: top left;
  transform: rotate(-25deg);
}
.needle-play {
  transform: rotate(2deg);
}
.record {
  display: flex;
  width: 500rpx;
  height: 500rpx;
  justify-content: center;
  align-items: center;
  position: relative;
  margin: auto;
  margin-top: -80px;
  background: url('../../static/images/disc.png') no-repeat;
  background-size: 500rpx 500rpx;
  .cover {
    position: relative;
    width: 320rpx;
    height: 320rpx;
    border-radius: 50%;
    animation: play 20s linear infinite;
  }
  .btn {
    opacity: 1;
    position: absolute;
    width: 400rpx;
    height: 400rpx;
    background: rgba(0, 0, 0, 0.2);
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    .iconfont {
      font-size: 50px;
    }
  }
}
.lyric-wrap {
  overflow: hidden;
  height: 246rpx;
  line-height: 82rpx;
  margin: 30px 0;
  .lyric {
    display: flex;
    flex-direction: column;
    align-items: center;
    overflow: hidden;
    transition: all 1s;

    .lyric-item {
      height: 82rpx;
      transition: all 0.5s;
    }
    .lyric-item-active {
      font-weight: 600;
      font-size: 16px;
      color: rgb(9, 171, 241);
    }
  }
}

@keyframes play {
  0% {
    -webkit-transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(360deg);
  }
}
</style>
